﻿using System;
using System.Threading;

namespace Q.Extensions
{
    public static class EventArgsExtensions
    {
        /// <summary>
        /// Raise an event in a thread-safe way.
        /// </summary>
        public static void Raise<TEventArgs>(this TEventArgs e,
            Object sender, ref EventHandler<TEventArgs> eventDelegate)
            where TEventArgs : EventArgs
        {
            //Copy delegate for thread safety.
            EventHandler<TEventArgs> temp = Interlocked.CompareExchange(
                ref eventDelegate, null, null);
            //Fire event.
            if (temp != null) temp(sender, e);
        }
    }
}
